﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MemCached;
namespace Common
{
    /// <summary>
    ///author：cjq
    ///remark:memcache 帮助类
    ///time:2013.04.24 19:23:00
    /// </summary>
    public class MemCachedHelper
    {
        const string CacheName = "ARCSOFTCR$MemCached";
        public static String MemCachedServerAddress
        {
            get
            {
                return System.Web.Configuration.WebConfigurationManager.AppSettings["MemCachedServer"];
            }
        }

        #region 添加缓存
        private static bool addCache(String Key, Object Value, TimeSpan? CacheTimeOut)
        {
            if (CacheTimeOut == null)
            {
                CacheTimeOut = TimeSpan.FromHours(2);
            }
            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "ARCSOFTCR$MemCached";
                MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Set(Key, Value, (TimeSpan)CacheTimeOut);
                }
            }
            else
            {
                return false;
            }
        }
        private static bool addCache(String Key, Object Value, TimeSpan? CacheTimeOut, string instanceName)
        {
            if (CacheTimeOut == null)
            {
                CacheTimeOut = TimeSpan.FromHours(12);
            }
            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "ARCSOFTCR$MemCached";
              MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
              if (cache == null)
              {
                  return false;
              }
              else
              {
                  return cache.Set(Key, Value, (TimeSpan)CacheTimeOut);
              }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="Key">缓存的Key值</param>
        /// <param name="Value">缓存的Value值</param>
        /// <returns></returns>
        public static bool AddCache(String Key, Object Value)
        {
            return addCache(Key, Value, null);
        }

        public static bool AddCache(String Key, Object Value, TimeSpan CacheTimeOut)
        {
            return addCache(Key, Value, CacheTimeOut);
        }

        public static bool AddCacheMutipleSystem(String Assembly, String Key, Object Value)
        {
            if (Assembly.Equals("DAL"))
                return AddCache(Key , Value);

            TimeSpan timeSpan = TimeSpan.FromHours(2);
            if (MemcachedClient.CheckKey(Key))
            {
                MemcachedClient cache = GetMemcachedClient(Assembly,CacheName, new string[] { System.Web.Configuration.WebConfigurationManager.AppSettings["MemCachedServer" + Assembly] });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Set(Key, Value, (TimeSpan)timeSpan);
                }
            }
            else
            {
                return false;
            }
        }

        public static bool AddCacheMutipleSystem(String Assembly, String Key, Object Value,TimeSpan ts)
        {
            if (Assembly.Equals("DAL"))
                return AddCache(Key, Value);
            if (ts == null)
            {
                ts = TimeSpan.FromHours(2);
            }
            if (MemcachedClient.CheckKey(Key))
            {
                MemcachedClient cache = GetMemcachedClient(Assembly, CacheName, new string[] { System.Web.Configuration.WebConfigurationManager.AppSettings["MemCachedServer" + Assembly] });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Set(Key, Value, (TimeSpan)ts);
                }
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 获取缓存
        public static Object GetCache(String Key)
        {

            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "MemCached";
               MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
               if (cache == null)
               {
                   return null;
               }
               else
               {
                   return cache.Get(Key);
               }
            }
            else
            {
                return null;
            }
        }
        public static Object GetCache(String Key, string instanceName)
        {

            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "MemCached";
                MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Get(Key);
                }
            }
            else
            {
                return null;
            }
        }
        public static Object GetCacheMutipleSystem(String Assembly,String Key)
        {
            if(Assembly.Equals("DAL"))
                return GetCache(Key);

            if (MemcachedClient.CheckKey(Key))
            {
                MemcachedClient cache = GetMemcachedClient(Assembly,CacheName, new string[] { System.Web.Configuration.WebConfigurationManager.AppSettings["MemCachedServer" + Assembly] });
                if (cache == null)
                {
                    return null;
                }
                else
                {
                    return cache.Get(Key);
                }
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 删除缓存
        public static bool DeleteCache(String Key)
        {
            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "MemCached";
                MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Delete(Key);
                }
            }
            else
            {
                return false;
            }
        }
        public static bool DeleteCache(String Key, string instanceName)
        {
            if (MemcachedClient.CheckKey(Key))
            {
                //String CacheName = "MemCached";
                MemcachedClient cache = GetMemcachedClient(CacheName, new string[] { MemCachedServerAddress });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Delete(Key);
                }
            }
            else
            {
                return false;
            }
        }
        public static bool DeleteCacheMutipleSystem(String Assembly, String Key)
        {
            if (Assembly.Equals("DAL"))
                return DeleteCache(Key);

            if (MemcachedClient.CheckKey(Key))
            {
                MemcachedClient cache = GetMemcachedClient(Assembly, CacheName, new string[] { System.Web.Configuration.WebConfigurationManager.AppSettings["MemCachedServer" + Assembly] });
                if (cache == null)
                {
                    return false;
                }
                else
                {
                    return cache.Delete(Key);
                }
            }
            else
            {
                return false;
            }
        }
        #endregion

        /// <summary>
        /// 获取缓存实例
        /// </summary>
        /// <param name="CacheInstanceName"></param>
        /// <param name="hosts"></param>
        /// <returns></returns>
        private static MemcachedClient GetMemcachedClient(String CacheInstanceName, String[] hosts)
        {
            MemcachedClient cache = null;
            #region 先移除实例，再创建实例
            //if (MemcachedClient.Exists(CacheInstanceName, hosts))
            //{
            //    cache = MemcachedClient.GetInstance(CacheInstanceName);
            //}
            //else
            //{
            //    Boolean bl = true;
            //    if (MemcachedClient.Exists(CacheInstanceName))
            //    {
            //        bl = MemcachedClient.RemoveInstances(CacheInstanceName);
            //    }
            //    if (bl)
            //    {
            //        MemcachedClient.Setup(CacheInstanceName, hosts);
            //        cache = MemcachedClient.GetInstance(CacheInstanceName);
            //        int SendReceiveTimeout = 2000;
            //        TimeSpan SocketRecycleAge = TimeSpan.FromHours(12);
            //        cache.SendReceiveTimeout = (Int32)SendReceiveTimeout;
            //        cache.SocketRecycleAge = SocketRecycleAge;
            //        cache.MinPoolSize = 1;
            //        cache.MaxPoolSize = 100;
            //    }

            //}
            #endregion
            
            if (MemcachedClient.Exists(CacheInstanceName))
            {
                cache = MemcachedClient.GetInstance(CacheInstanceName);
            }
            else
            {
                MemcachedClient.Setup(CacheInstanceName, hosts);
                cache = MemcachedClient.GetInstance(CacheInstanceName);
                int SendReceiveTimeout = 2000;
                TimeSpan SocketRecycleAge = TimeSpan.FromHours(12);
                cache.SendReceiveTimeout = (Int32)SendReceiveTimeout;
                cache.SocketRecycleAge = SocketRecycleAge;
                cache.MinPoolSize = 1;
                cache.MaxPoolSize = 100;
            }

            return cache;
        }
        /// <summary>
        /// 获取缓存实例
        /// </summary>
        /// <param name="Assembly"></param>
        /// <param name="CacheInstanceName"></param>
        /// <param name="hosts"></param>
        /// <returns></returns>
        private static MemcachedClient GetMemcachedClient(String Assembly, String CacheInstanceName, String[] hosts)
        {
            MemcachedClient cache = null;

            if (MemcachedClient.Exists(Assembly,CacheInstanceName))
            {
                cache = MemcachedClient.GetInstance(Assembly, CacheInstanceName);
            }
            else
            {
                MemcachedClient.Setup(Assembly, CacheInstanceName, hosts);
                cache = MemcachedClient.GetInstance(Assembly, CacheInstanceName);
                int SendReceiveTimeout = 2000;
                TimeSpan SocketRecycleAge = TimeSpan.FromHours(12);
                cache.SendReceiveTimeout = (Int32)SendReceiveTimeout;
                cache.SocketRecycleAge = SocketRecycleAge;
                cache.MinPoolSize = 1;
                cache.MaxPoolSize = 100;
            }

            return cache;
        }
    }
}
